//package cn.com.w.ratelimiter.util;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.google.common.collect.Maps;
//import com.koolearn.clue.sea.api.IToDistributeCluePoolService;
//import com.koolearn.clue.sea.api.mq.RocketMqPushService;
//import com.koolearn.clue.sea.common.ClueMqProducer;
//import com.koolearn.clue.sea.common.FutureRecycleMqPushService;
//import com.koolearn.clue.sea.config.AppConfig;
//import com.koolearn.clue.sea.dao.ClueSaleMapper;
//import com.koolearn.clue.sea.dao.ForbidDistributeCluePoolMapper;
//import com.koolearn.clue.sea.dao.ToDistributeCluePoolMapper;
//import com.koolearn.clue.sea.enums.*;
//import com.koolearn.clue.sea.model.dto.mq.FutureRecycleMQDTO;
//import com.koolearn.clue.sea.service.EsSynchroService;
//import com.koolearn.clue.sea.service.ForbidDistributeCluePoolLocalService;
//import com.koolearn.clue.sea.utils.RateLimiterUtil;
//import com.koolearn.crm2.sea.model.PeBigDataClueScore;
//import com.koolearn.crm2.sea.model.dto.AutoDistributeMQDTO;
//import com.koolearn.crm2.system.enums.DistributeReasonEnum;
//import com.koolearn.framework.rocketmq.client.common.ConsumerCallback;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.StringUtils;
//import org.apache.rocketmq.common.message.MessageExt;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.util.Date;
//import java.util.HashMap;
//import java.util.Random;
//
//
//@Slf4j
//@Component("bigDataClueScoreConsumer")
//public class BigDataClueScoreConsumer implements ConsumerCallback{
//
//    @Autowired
//    private ClueSaleMapper clueSaleMapper;
//
//    @Autowired
//    private EsSynchroService esSynchroService;
//
//    @Autowired
//    private ToDistributeCluePoolMapper toDistributeCluePoolMapper;
//    @Autowired
//    private ForbidDistributeCluePoolMapper forbidDistributeCluePoolMapper;
//    @Autowired
//    private FutureRecycleMqPushService futureRecycleMqPushService;
//
//    @Autowired
//    private ForbidDistributeCluePoolLocalService forbidDistributeCluePoolLocalService;
//
//    @Autowired
//    private IToDistributeCluePoolService toDistributeCluePoolService;
//
//
//    @Autowired
//    private RocketMqPushService rocketMqPushService;
//    @Autowired
//    private ClueMqProducer clueMqProducer;
//
//    @Override
//    public void call(Object entity, Object o2){
//        // 1、放弃开关打开时直接丢弃数据,为防止CPU和load飙升，通过sleep控制过快的丢弃
//        if (AppConfig.getBigScoreRateLimiterGiveUp().equals("1")) {
//            log.info("clueScoreConsumer limit Give Up");
//            try{
//                int time = AppConfig.getBigScoreGiveUpSleepTime();
//                Thread.sleep(time);
//            }catch (Exception e){
//                log.error("clueScoreConsumer Thread.sleep Exception!", e);
//            }
//            return;
//        }
//        // 2、处理受限扔回队列，为防止CPU和load飙升，通过sleep控制扔回队列的速度
//        if(!RateLimiterUtil.bigScoreTryAcquire()) {
//            log.info("clueScoreConsumer limited, put message back");
//            try{
//                Random r = new Random();
//                int nextInt = r.nextInt(100) + 10;
//                Thread.sleep(nextInt);
//            }catch (Exception e){
//                log.error("clueScoreConsumer Thread.sleep Exception!", e);
//            }
//            throw new RuntimeException("clueScoreConsumer limit put message！");
//        }
//
//        Long start = System.currentTimeMillis();
//        MessageExt k = (MessageExt)o2;
//        log.info("clueScoreConsumer,msg:{}, msgExt:{}", entity, k);
//        JSONObject clueScore = JSONObject.parseObject(entity.toString());
//        PeBigDataClueScore peBigDataClueScore = buildClueScoreObj(clueScore);
//        Integer clueId = peBigDataClueScore.getClueId();
//        if (clueId != null) {
//            setClueScoreIfNecessary(peBigDataClueScore);
//        }else{
//            log.warn("clueScoreConsumer.call execute failed,info:{}", JSON.toJSONString(peBigDataClueScore));
//        }
//        log.info("clueScoreConsumer.call execute end! info:{} cost:{}ms", JSON.toJSONString(peBigDataClueScore), System.currentTimeMillis() - start);
//    }
//
//    /**
//     *  对象互转
//     * @param clueScore json实体
//     */
//    private PeBigDataClueScore buildClueScoreObj(JSONObject clueScore) {
//        //格式{"clue_id":"1032597","user_id":"80854504","clue_pool_code":"9","score":42.15,"data_version":"v1","dt":"20200526"}
//        PeBigDataClueScore peBigDataClueScore = new PeBigDataClueScore();
//        try {
//            peBigDataClueScore.setScore(clueScore.getDouble("score"));
//            peBigDataClueScore.setClueId(clueScore.getInteger("clue_id"));
//            peBigDataClueScore.setUserId(clueScore.getInteger("user_id"));
//            peBigDataClueScore.setPoolIndex(clueScore.getInteger("clue_pool_code"));
//            peBigDataClueScore.setModelVersion(clueScore.getString("data_version"));
//            peBigDataClueScore.setDt(clueScore.getDate("dt"));
//        } catch (Exception e) {
//            log.error("parse clue score json error：",e);
//            throw new IllegalArgumentException(e);
//        }
//        return peBigDataClueScore;
//    }
//
//    /**
//     * 设置线索评分
//     * @param peBigDataClueScore
//     */
//    private void setClueScoreIfNecessary(PeBigDataClueScore peBigDataClueScore) {
//        Integer clueId = peBigDataClueScore.getClueId();
//        String modelVersion = peBigDataClueScore.getModelVersion();
//        String versions = AppConfig.getClueBigDataScoreModelVersion();
//        if (StringUtils.isEmpty(versions)){
//            log.warn("clue-big-data-score-model-version is empty,clueId:{},version:{}",clueId,modelVersion);
//            return;
//        }
//        Integer poolIndex = peBigDataClueScore.getPoolIndex();
//        if (poolIndex == null){
//            log.warn("poolIndex is empty,clueId:{},version:{}",clueId,modelVersion);
//            return;
//        }
//
//        try{
//            JSONObject poolVersion = JSONObject.parseObject(versions);
//            String version = poolVersion.getString(String.valueOf(poolIndex));
//            if (StringUtils.isNotEmpty(version) && version.equals(modelVersion)){
//                //设置线索表的评分
//                int result = this.updateClueScoreByClueId(clueId, peBigDataClueScore.getScore());
//                if(result <= 0){
//                    return;
//                }
//                // 发送即将回收线索评分
//                FutureRecycleMQDTO dto = new FutureRecycleMQDTO();
//                dto.setClueId(clueId);
//                dto.setScore(peBigDataClueScore.getScore());
//                futureRecycleMqPushService.sendFutureRecycleMQ(ClueSeaRocketMqTags.ChangeScore,dto);
//                // 校验待分配池和禁止手动分配池中的数据，发送规则匹配的消息
//                this.dealDistributeClueScore(clueId);
//                // 标签匹配
//                clueMqProducer.sendMatchClueLabelRuleMQ(clueId, null, ClueLabelMatchTypeEnum.SCORE_UPDATE.getCode(), ClueSeaRocketMqTags.LabelRuleMatch.getTag(), "AbstractHandlerMQ.createClue", null);
//
//            }else{
//                log.warn("clue version is empty,clueId:{},version:{}",clueId,modelVersion);
//            }
//
//        }catch (Exception e){
//            log.error("error:{}",e);
//        }
//
//    }
//
//    /**
//     * 校验待分配池和禁止手动分配池中的数据，发送规则匹配的消息
//     * @param clueId
//     */
//    private void dealDistributeClueScore(Integer clueId){
//        if(!AppConfig.geChangeScoreAffectDistributePoolSwitch()){
//            return;
//        }
//        Integer existsDistribute = toDistributeCluePoolMapper.existUnallocated(clueId);
//        Integer existsForbid = forbidDistributeCluePoolMapper.existsForbidHandDistribute(clueId);
//        AutoDistributeMQDTO autoDistributeMQDTO = new AutoDistributeMQDTO();
//        autoDistributeMQDTO.setClueId(clueId);
//        autoDistributeMQDTO.setCreateTime(new Date());
//        autoDistributeMQDTO.setDistributeReason(DistributeReasonEnum.CHANGE_SCORE.getCode());
//        if(null != existsDistribute || null != existsForbid){
//            try{
//                toDistributeCluePoolService.cancelDistributeClue(clueId,CancelToDistributeClueReasonEnum.CHANGE_SCORE_CANCEL);
//                forbidDistributeCluePoolLocalService.cancelForbidDistribute(clueId,CancelToDistributeClueReasonEnum.CHANGE_SCORE_CANCEL);
//            } catch (Exception e){
//                log.error("ClueMatchService.dealDistributeClueScore error clueId = {},clueMatchEnum = {}",clueId,CancelToDistributeClueReasonEnum.CHANGE_SCORE_CANCEL,e);
//            }
//        }
//        rocketMqPushService.clueDistribute(ClueSeaRocketMqTags.ClueDistributeSendMessage, autoDistributeMQDTO);
//    }
//
//    private int updateClueScoreByClueId(Integer clueId, Double clueScore) {
//        int result = clueSaleMapper.updateClueScoreByClueId(clueId, clueScore);
//        if (result == 0) {
//            return result;
//        }
//        HashMap<String, Object> map = Maps.newHashMap();
//        map.put("dm_id", clueId);
//        map.put("clue_score", clueScore);
//        esSynchroService.saveSynchro(map, SynchroMethodEnum.UPDATE, SynchroBusinessEnum.CLUE,clueId,"bigDataClueScoreConsumer.updateClueScoreByClueId");
//        return result;
//    }
//}
